﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Relocation.Data;
using System.Data.Objects;
using Relocation.Com.Tools;
using Relocation.Com;
using System.Threading;
using System.Collections.Generic;
using Relocation.UI.Interface;
using Relocation.Base;
using Relocation.UI.Xls;
using Relocation.UI.Relocate;


namespace Relocation.UI
{
	public partial class RelocateesList : RelocateesListHelp, IPrintForm
	{
		#region 构造函数

		public RelocateesList()
			: base()
		{
			InitializeComponent();
			Initialize();
		}

		public RelocateesList(Session session)
			: base(session)
		{
			InitializeComponent();
			Initialize();
		}

		#endregion

		#region 初始化

		public void Initialize()
		{
			this.relocateesDataGridView.init();	//多行表头初始化

			this.SortField = relocatees_view.GetPropName(t => t.updated);
			this.ObjectQuery = this.Session.DataModel.relocatees_view.Where("it.project_id==" + this.Session.Project.project_id);
			//数据绑定变更事件
			this.BindingSource.DataSourceChanged += new System.EventHandler(this.relocateesBindingSource_DataSourceChanged);
			//单元格格式化事件
			this.relocateesDataGridView.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.relocateesDataGridView_CellFormatting);

			this.S_comboBoxOrganization.Tag = new ControlTag(null, null, new SearchInfo(relocatees_view.GetPropName(t => t.organization)));
			this.S_comboBoxVillage.Tag = new ControlTag(null, null, new SearchInfo(relocatees_view.GetPropName(t => t.village)));
			this.S_textBox2.Tag = new ControlTag(null, null, new SearchInfo(relocatees_view.GetPropName(t => t.head)));
			this.S_comboBoxStatus.Tag = new ControlTag(null, null, new SearchInfo(relocatees_view.GetPropName(t => t.status), SearchInfo.SearchFieldTypes.Number, new SearchInfo.RanderHandler(delegate(Control conrol) {
				if (conrol == null)
					return "";
				ComboBox box = conrol as ComboBox;
				if (box == null)
					return "";
				int selectIndex = box.SelectedIndex;
				switch (selectIndex)
				{
					case 0:
						return "";
					case 1:
						return "0";
					case 2:
						return "1";
					case 3:
						return "2";
					default:
						return "";
				}

			}), new SearchInfo.ReseterHandler(delegate(Control control) {
				ComboBox box = control as ComboBox;
				if (box != null)
					box.SelectedIndex = 0;
			})));
			ControlTag tag = new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN, Session.KEY_ROLE_OPERATOR));
			this.ButtonAdd.Tag = tag;
			this.ButtonEdit.Tag = tag;
			this.ButtonDel.Tag = tag;
			InitCombobox();	//加载下拉框
			this.FieldIsChanged = false;

		}

		/// <summary>
		/// 加载村别和单位的下拉框
		/// </summary>
		private void InitCombobox()
		{
			ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj) {
				ObjectQuery<Relocatee> _Relocatees = this.Session.Project.Relocatees.CreateSourceQuery();
				List<string> villageList = _Relocatees.Where(it => !string.IsNullOrEmpty(it.village)).OrderByDescending(t => t.updated).Select(x => x.village).Distinct().ToList();
				villageList.Insert(0, string.Empty);
				this.ExecMethodInvoker(new MethodInvoker(delegate() {
					this.S_comboBoxVillage.DataSource = villageList;
					S_comboBoxVillage_TextChanged(null, null);	//加载村庄下面的单位下拉框
				}));
			}));

		}


		/// <summary>
		/// 村别改变时加载单位的下拉框
		/// </summary>		
		private void S_comboBoxVillage_TextChanged(object sender, EventArgs e)
		{
			
			string villageName = this.S_comboBoxVillage.Text.Trim();
			bool villageIsNull = string.IsNullOrEmpty(villageName);
			ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj) {

				List<string> list;
				if (villageIsNull)
					list = this.Session.DataModel.getRelocateesByProjectId(this.Session.Project.project_id).Select(x => x.organization).Distinct().ToList();
				else
					list = this.Session.DataModel.getRelocateesByProjectId(this.Session.Project.project_id).Where(it => it.village.Equals(villageName)).Select(x => x.organization).Distinct().ToList();
				list.Insert(0, string.Empty);
				this.ExecMethodInvoker(new MethodInvoker(delegate() {
					string organization = this.S_comboBoxOrganization.Text;
					this.S_comboBoxOrganization.DataSource = list;
					this.S_comboBoxOrganization.Text = organization;
				}));
			}));

		}



		#endregion

		#region 增、删、改按钮事件


		/// <summary>
		/// 添加拆迁户信息
		/// </summary>
		private void add_Click(object sender, EventArgs e)
		{
			try
			{
				using (RelocateesWindow RelocateesWindow = new RelocateesWindow(this.Session))
				{
					RelocateesWindow.MaximizeBox = false;
					RelocateesWindow.MinimizeBox = false;
					RelocateesWindow.MaximumSize = new System.Drawing.Size(830, 400);
					RelocateesWindow.MinimumSize = new System.Drawing.Size(830, 400);
					DialogResult DialogResult = RelocateesWindow.ShowDialog();
					if (DialogResult.Equals(DialogResult.OK))
						this.Refresh();
				}
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error(ex.Message);
			}
		}

		/// <summary>
		/// 修改选中的某一项
		/// </summary>
		private void edit_Click(object sender, EventArgs e)
		{
			try
			{
				Relocatee relocation = this.GetSelectEntity();
				if (relocation == null)
					return;
				//Session.DataModel.RefreshNode(System.Data.Objects.RefreshMode.StoreWins, relocation);
				//relocation.ProjectsReference.Load();
				using (RelocateesWindow RelocateesWindow = new RelocateesWindow(this.Session, relocation))
				{
					RelocateesWindow.Text = "拆迁户修改";
					RelocateesWindow.MaximizeBox = false;
					RelocateesWindow.MinimizeBox = false;
					RelocateesWindow.MaximumSize = new System.Drawing.Size(830, 400);
					RelocateesWindow.MinimumSize = new System.Drawing.Size(830, 400);
					DialogResult DialogResult = RelocateesWindow.ShowDialog();
					if (DialogResult.Equals(DialogResult.OK))
					{
						Session.DataModel.Refresh(System.Data.Objects.RefreshMode.StoreWins, (relocatees_view)this.BindingSource.Current);
						this.Refresh();
					}
				}

			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error(ex);
			}
		}

		public new Relocatee GetSelectEntity()
		{
			relocatees_view relocatees_view = base.GetSelectEntity();
			if (relocatees_view == null)
				return null;
			return this.Session.DataModel.getRelocateesById(relocatees_view.relocatees_id);
		}

		/// <summary>
		/// 删除选中项
		/// </summary>
		private void del_Click(object sender, EventArgs e)
		{
			try
			{
				Relocatee relocatees = this.GetSelectEntity();
				if (relocatees == null)
					return;
				this.Session.DataModel.Refresh(RefreshMode.ClientWins, relocatees);

				TreeNode node = this.Session.GetMainTreeView().FindNode(relocatees);
				if (node != null)
					this.Session.GetMainTreeView().deleteRelocatees(node);
				else
					Log.Error("Relocatees节点未找到");

			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				MyMessagebox.Error("删除失败！");
			}
			this.Refresh();
		}

		#endregion



		#region 数据加载相关事件


		/// <summary>
		/// Relocatees_View页面刷新
		/// </summary>
		public override void Refresh()
		{
			if (this.IsDisposed)
				return;
			try
			{
				this.Reload();
				this.InitCombobox();
			} catch (Exception ex)
			{
				Log.Error(Tools.GetExceptionMessage(ex));
			}
		}

		/// <summary>
		/// 格式化单元格的信息
		/// </summary>		
		private void relocateesDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			string name = this.relocateesDataGridView.Columns[e.ColumnIndex].Name;//.DataPropertyName;			
			if (name.Equals(this.status.Name))
			{
				string value = e.Value as string;
				if (string.IsNullOrEmpty(value))
					e.Value = "未安置";
				else if (value.Equals("1"))
					e.Value = "安置中";
				else if (value.Equals("2"))
					e.Value = "已安置";
				else
					e.Value = "";
				e.FormattingApplied = true;
			} else if (name.Equals(this.index.Name) && (e.Value == null))
			{
				e.Value = (e.RowIndex + 1).ToString();
				e.FormattingApplied = true;
			} else if (name.Equals(this.persons_notrel.Name))
			{
				if (Convert.ToDecimal(e.Value) != 0M)
					e.CellStyle.BackColor = Color.Red;
				e.FormattingApplied = false;

			} else if (name.Equals(this.persons_rel.Name))
			{
				if (Convert.ToDecimal(e.Value) != 0M)
					this.relocateesDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.SteelBlue;
				e.FormattingApplied = false;

			} else if ((name.Equals(this.housetype1.Name) ||
				name.Equals(this.housetype2.Name)) ||
				name.Equals(this.housetype3.Name) ||
				name.Equals(this.housetype4.Name) ||
				name.Equals(this.housetype5.Name) ||
				name.Equals(this.housetype6.Name) ||
				name.Equals(this.housetype7.Name))
			{
				if (Convert.ToDecimal(e.Value) != 0M)
					e.CellStyle.BackColor = Color.Red;
				e.FormattingApplied = false;

			} else if ((name.Equals(this.type0.Name) ||
				name.Equals(this.type1.Name)) ||
				name.Equals(this.type2.Name) ||
				name.Equals(this.type3.Name) ||
				name.Equals(this.type4.Name) ||
				name.Equals(this.type5.Name) ||
				name.Equals(this.type6.Name))
			{
				if (Convert.ToDecimal(e.Value) != 0M)
					e.CellStyle.BackColor = Color.Red;
				e.FormattingApplied = false;

			} else if (name.Equals(this.buy1.Name) || name.Equals(this.buy2.Name) || name.Equals(this.buy3.Name))
			{
				e.Value = Convert.ToBoolean(e.Value) ? "√" : "";
				e.FormattingApplied = true;
			}
		}

		/// <summary>
		/// 当绑定数据时刷新序号
		/// </summary>		
		private void relocateesBindingSource_DataSourceChanged(object sender, EventArgs e)
		{
			WaitForm WaitForm = new WaitForm("请等待", "数据加载中，请稍候...");
			WaitForm.Tag = false;
			ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o) {
				relocatees_view RelocateesTotal = new relocatees_view();
				try
				{
					if (this.relocateesDataGridView.Rows.Count < 1)
					{
						//拆迁补偿款
						RelocateesTotal.money1 = 0;
						//房屋统拆补助
						RelocateesTotal.money2 = 0;
						//拆迁奖励
						RelocateesTotal.money3 = 0;
						//小计
						RelocateesTotal.total = 0;
						//货币化安置款
						RelocateesTotal.payment = 0;
						//安置人数：意向
						RelocateesTotal.persons = 0;
						//安置人数：已安置     
						RelocateesTotal.persons_rel = 0;
						//安置人数：未安置
						RelocateesTotal.persons_notrel = 0;
						//意向安置户型：70
						RelocateesTotal.housetype1 = 0;
						//意向安置户型：90
						RelocateesTotal.housetype2 = 0;
						//意向安置户型：110
						RelocateesTotal.housetype3 = 0;
						//意向安置户型：130
						RelocateesTotal.housetype4 = 0;
						//已安置户型：70
						RelocateesTotal.type0 = 0;
						//已安置户型：90
						RelocateesTotal.type1 = 0;
						//已安置户型：110
						RelocateesTotal.type2 = 0;
						//已安置户型：130
						RelocateesTotal.type3 = 0;
						//将状态设为-1，以免被格式化
						RelocateesTotal.status = -1;
						RelocateesTotal.area = 0;
					} else
					{
						//拆迁补偿款
						RelocateesTotal.money1 = this.ObjectQuerySearch.Sum(t => t.money1);
						//房屋统拆补助
						RelocateesTotal.money2 = this.ObjectQuerySearch.Sum(t => t.money2);
						//拆迁奖励
						RelocateesTotal.money3 = this.ObjectQuerySearch.Sum(t => t.money3);
						//小计
						RelocateesTotal.total = this.ObjectQuerySearch.Sum(t => t.total);
						//货币化安置款
						RelocateesTotal.payment = this.ObjectQuerySearch.Sum(t => t.payment);
						//安置人数：意向
						RelocateesTotal.persons = this.ObjectQuerySearch.Sum(t => t.persons);
						//安置人数：已安置  #####如果记录为空的时候会出现异常
						RelocateesTotal.persons_rel = this.ObjectQuerySearch.Sum(t => t.persons_rel);
						//安置人数：未安置
						RelocateesTotal.persons_notrel = RelocateesTotal.persons - RelocateesTotal.persons_rel;
						//RelocateesCollection.Sum(t => t.persons_rel);
						//意向安置户型：70
						RelocateesTotal.housetype1 = this.ObjectQuerySearch.Sum(t => t.housetype1);
						//意向安置户型：90
						RelocateesTotal.housetype2 = this.ObjectQuerySearch.Sum(t => t.housetype2);
						//意向安置户型：110
						RelocateesTotal.housetype3 = this.ObjectQuerySearch.Sum(t => t.housetype3);
						//意向安置户型：130
						RelocateesTotal.housetype4 = this.ObjectQuerySearch.Sum(t => t.housetype4);
						//已安置户型：70
						RelocateesTotal.type0 = this.ObjectQuerySearch.Sum(t => t.type0);
						//已安置户型：90
						RelocateesTotal.type1 = this.ObjectQuerySearch.Sum(t => t.type1);
						//已安置户型：110
						RelocateesTotal.type2 = this.ObjectQuerySearch.Sum(t => t.type2);
						//已安置户型：130
						RelocateesTotal.type3 = this.ObjectQuerySearch.Sum(t => t.type3);
						RelocateesTotal.area = this.ObjectQuerySearch.Sum(t => t.area);
						//将状态设为-1，以免被格式化
						RelocateesTotal.status = -1;
					}

				} catch (Exception ex)
				{
					Log.Error(Tools.GetExceptionMessage(ex));
				}
				this.Invoke(new MethodInvoker(delegate() {
					try
					{
						WaitForm _WaitForm = (WaitForm)o;
						_WaitForm.Tag = true;
						_WaitForm.Close();
						this.relocateesDataGridView.Visible = true;
						this.BindingSource.Add(RelocateesTotal);
						this.relocateesDataGridView.Rows[this.relocateesDataGridView.RowCount - 1].Cells[this.index.Name].Value = "总计：";
					} catch (Exception ex)
					{
						Log.Error(Tools.GetExceptionMessage(ex));
					}

				}));

			}), WaitForm);
			if (!(bool)WaitForm.Tag)
			{
				this.relocateesDataGridView.Visible = false;
				WaitForm.ShowDialog();
			}
		}

		#endregion

		#region DataGridView事件

		/// <summary>
		/// 双击显示安置房及交款情况
		/// </summary>
		protected override void DataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex != -1)
			{
				this.ButtonEdit.PerformClick();
			}
		}

		#endregion

		#region 其他方法

		/// <summary>
		/// 更加状态显示不同的颜色
		/// </summary>
		/// <param name="cell">单元格</param>
		/// <param name="state">状态代号（0：未安置，1：安置中，2：已安置）</param>
		public void SetCellColor(DataGridViewCell cell, int state)
		{
			this.ExecMethodInvoker(new MethodInvoker(delegate() {
				if (state == 0)
				{
					cell.Style.BackColor = SystemColors.GradientActiveCaption;
				} else if (state == 1)
				{
					cell.Style.BackColor = Color.Tan;
				} else if (state == 2)
				{
					//cell.Style.BackColor = Color.Yellow;
				}
			}));
		}


		#endregion

		#region IPrintForm 成员

		public void Print()
		{
            PrintSelectWindow printSelectWindow = new PrintSelectWindow();
            if (printSelectWindow.ShowDialog().IsOK())
            {
                if (PrintSelectWindow.PrintTypes.Detail.Equals(printSelectWindow.PrintType))
                    Relocation.Com.Tools.ExcelHelp.DataGridToExcel(this.relocateesDataGridView);
                else
                    RelocateToExcel.RelocateViewToExcel(this.ObjectQuerySearch.ToList());
            }			
		}

		#endregion

	}
}


